PGFPlots¶

This library uses the LaTeX package pgfplots to produce plots. It integrates with IJulia, outputting SVG images to the notebook. This version of PGFPlots requires Julia 1.0 or later.

Installation¶

Pkg.add("PGFPlots")

In addition, you will need to install the following dependencies if you do not already have them on your system.

  • Pdf2svg. This is required by TikzPictures. On Ubuntu, you can get this by running sudo apt-get install pdf2svg and on RHEL/Fedora by running sudo dnf install pdf2svg. On Windows, you can download the binaries from http://www.cityinthesky.co.uk/opensource/pdf2svg/. Be sure to add pdf2svg to your path (and restart).
  • Pgfplots (version 1.10 or later). Install using your latex package manager (e.g., texlive or miktex).

Once these things are installed, you should be able to run the following:

In [1]:
using PGFPlots
[ Info: Precompiling PGFPlots [3b7a836e-365b-5785-a47d-02c71176b4aa] (cache misses: wrong dep version loaded (2), wrong source (2), dep uuid changed (2))
WARNING: could not import TikzPictures.@L_mstr into PGFPlots

Examples¶

Linear Plots¶

You can create a very basic plot by passing in vectors of $x$ and $y$ coordinates.

In [2]:
x = [1,2,3]
y = [2,4,1]
plot(x, y)
Out[2]:
No description has been provided for this image

You can also inspect the tikz code that is generated for any plot.

Note that you can also store plots directly as .tex files instead of inspecting their code as Strings (see Saving below)

In [3]:
print(tikzCode(x, y))
\begin{axis}

\addplot+ coordinates {
  (1, 2)
  (2, 4)
  (3, 1)
};

\end{axis}

The version of the plot function above actually just creates an empty Axis and inserts a Plots.Linear instance containing the data.

In [4]:
Axis(Plots.Linear(x, y))
Out[4]:
No description has been provided for this image

If you create the Axis object explicitly, as done above, then you can set various properties of the axis.

In [5]:
pushPGFPlotsOptions("scale=1.5")
a = Axis(Plots.Linear(x, y, legendentry="My Plot"), xlabel="X", ylabel="Y", title="My Title")
Out[5]:
No description has been provided for this image

The options can be set after the plot a is created. Here we rotate the y-label and move the legend by setting the ylabelStyle and legendStyle:

In [6]:
a.ylabelStyle = "rotate = -90"
a.legendStyle = "at={(1.05,1.0)}, anchor=north west"
a
Out[6]:
No description has been provided for this image
In [7]:
print(tikzCode(a))
\begin{axis}[
  legend style = {at={(1.05,1.0)}, anchor=north west},
  ylabel = {Y},
  ylabel style = {rotate = -90},
  title = {My Title},
  xlabel = {X}
]

\addplot+ coordinates {
  (1, 2)
  (2, 4)
  (3, 1)
};
\addlegendentry{{}{My Plot}}

\end{axis}

This will remove the latest added setting

In [8]:
popPGFPlotsOptions();

And to reset all options, use

In [9]:
resetPGFPlotsOptions();

You can set the width and height of the axis.

In [10]:
Axis(Plots.Linear(x, y), width="3cm", height="3cm")
Out[10]:
No description has been provided for this image

Since latex is used to typeset everything, you can use any latex math symbols you want. If you use L"..." (as below), you do not have to escape \ and $.

In [11]:
Axis(Plots.Linear(x, y), xlabel=L"$X$", ylabel=L"$Y$", title=L"$\int_0^\infty e^{\pi x}dx$")
Out[11]:
No description has been provided for this image

It is possible to pass a dictionary with arbitrary options to the axis with the customOptions keyword:

You can pass in a function and its domain. It will automatically be evaluated based on the provided domain atxbins evenly-spaced points.

In [12]:
Plots.Linear(x->sqrt(2*x) + sin(x), (0,10), xbins=51)
Out[12]:
No description has been provided for this image

You can put multiple plots on the same axis and assign legend entries.

In [13]:
Axis([
    Plots.Linear(sin, (0,10), legendentry=L"\sin(x)"),
    Plots.Linear(x->sqrt(2*x), (0,10), legendentry=L"\sqrt{2x}")
])
Out[13]:
No description has been provided for this image

You can change the legend position by setting the legendPos parameter in the axis.

In [14]:
Axis([
    Plots.Linear(sin, (0,10), legendentry=L"\sin(x)"),
    Plots.Linear(x->sqrt(2*x), (0,10), legendentry=L"\sqrt{2x}")
    ], legendPos="north west")
Out[14]:
No description has been provided for this image

Not all entries need to have legends. The "forget plot" option can be used to skip a plot. Note that "forget plot" does not advance the cycle list color.

In [15]:
Axis([
    Plots.Linear(sin, (0,10), style="red", legendentry=L"\sin(x)"),
    Plots.Linear(x->sqrt(2*x), (0,10), style="blue, forget plot"),
    Plots.Linear(x->3exp(-x), (0,10), style="green", legendentry=L"3 \exp{-x}")
])
Out[15]:
No description has been provided for this image

You can do comb plots by setting the style. The style string gets passed directly into PGFPlots, giving you full control over the plots (see PGFPlots documentation).

In [16]:
Plots.Linear(1:10, sin.(1:10), style="ycomb")
Out[16]:
No description has been provided for this image

You can also do horizontal comb plots.

In [17]:
Plots.Linear(abs.(sin.(1:10)), 1:10, style="xcomb")
Out[17]:
No description has been provided for this image

You can also make it smooth.

In [18]:
Plots.Linear(1:10, sin.(1:10), style="smooth")
Out[18]:
No description has been provided for this image

There is support for constant plots.

In [19]:
Plots.Linear(1:10, sin.(1:10), style="const plot")
Out[19]:
No description has been provided for this image
In [20]:
Plots.Linear(1:10, sin.(1:10), style="ybar")
Out[20]:
No description has been provided for this image
In [21]:
Plots.Linear(1:10, sin.(1:10), style="ybar,fill=green", mark="none")
Out[21]:
No description has been provided for this image

You can give an axis a log scale by specifying xmode or ymode parameters of Axis:

In [22]:
p = Plots.Linear(0.01:0.01:1, 10 .^(0.01:0.01:1), mark="none")
Axis(p, ymode="log")
Out[22]:
No description has been provided for this image

Fill and fill opacity can be handled through the style parameter.

In [23]:
p = Plots.Linear(0:10, (0:10).^2, style="red, fill=blue, fill opacity=0.3", mark="none")
Out[23]:
No description has been provided for this image

If you want the tick marks to be equal, you can set axisEqual to true (equivalent to axis equal in LaTeX). Note that this will also change the limit sizes, over riding xmax, xmin, ymin, and ymax.

In [24]:
p = Plots.Linear(0:10, 2*(0:10))
Axis(p, axisEqual=true, xmin=0, xmax=10) # note xmin and xmax are disregarded...
Out[24]:
No description has been provided for this image

If this flippant disregard of your axis limit authority displeases you, you can set axisEqualImage to true (equivalent to axis equal image). This will leave the limits alone, and let you modify them.

In [25]:
p = Plots.Linear(0:10, 2*(0:10))
Axis(p, axisEqualImage=true)
Out[25]:
No description has been provided for this image

You can change the size of the markers with the markSize argument. The default marker size is 2.

In [26]:
Plots.Linear(0:10, 2*(0:10), markSize=10)
Out[26]:
No description has been provided for this image

To eliminate the line and only use marks, you can set the onlyMarks argument to true.

In [27]:
Plots.Linear(0:10, 2*(0:10), onlyMarks=true)
Out[27]:
No description has been provided for this image

Discrete Linear¶

We can associate values with an integer range, which defaults to starting at 1, and produce a piecewise constant plot.

In [28]:
Plots.DiscreteLinear([3,1,4,1,5,9,2,6,5])
Out[28]:
No description has been provided for this image

We can start at integer values other than 1 by using the start keyword. We can also adjust the style of the plot.

In [29]:
Plots.DiscreteLinear([3,1,4,1,5,9,2,6,5]; start=0, style="no marks")
Out[29]:
No description has been provided for this image

Stacked Plots¶

Here are a couple plots before they are stacked.

In [30]:
Axis([
    Plots.Linear(x->sin(x), (0,2)),
    Plots.Linear(x->abs(1.5*sin(2x)^2), (0,2))
])
Out[30]:
No description has been provided for this image

We can stack plots by setting the appropriate style.

In [31]:
Axis([
    Plots.Linear(x->sin(x), (0,2)),
    Plots.Linear(x->abs(1.5*sin(2x)^2), (0,2))
], style="stack plots=y")
Out[31]:
No description has been provided for this image

We can create area plots like this.

In [32]:
Axis([
    Plots.Linear(x->sin(x), (0,2), closedCycle=true),
    Plots.Linear(x->abs(1.5*sin(2x)^2), (0,2), closedCycle=true)
], style="stack plots=y, area style, enlarge x limits=false", ymin=0)
Out[32]:
No description has been provided for this image

Error Bars¶

You can plot error bars for Linear and Scatter plots. Here we specify an array for the y error.

In [33]:
x = [1,2,3]
y = [2,4,1]
plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5]))
Out[33]:
No description has been provided for this image

The y error does not have to be symmetric.

In [34]:
plot(x, y, errorBars = ErrorBars(yplus=[1, 0.3, 0.5], yminus=[0.5, 0.1, 0.1]))
Out[34]:
No description has been provided for this image

You can also specify x error.

In [35]:
plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5], x=[0.1, 0.1, 0.05]))
Out[35]:
No description has been provided for this image

You can change the style.

In [36]:
plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5], style="red,very thick"))
Out[36]:
No description has been provided for this image

You can also specify the mark.

In [37]:
plot(x, y, errorBars = ErrorBars(y=[1, 0.3, 0.5], mark="diamond"))
Out[37]:
No description has been provided for this image

You can control the style of the plot line along with the error bars.

In [38]:
plot(x, y, style="red", errorBars = ErrorBars(y=[1, 0.3, 0.5], style="black,very thick", mark="diamond"))
Out[38]:
No description has been provided for this image

Scatter Plots¶

A simple scatter plot is just a linear plot with "only marks". The following code returns a Linear plot with "only marks" selected:

In [39]:
x = 1:10
y = 2x
Plots.Scatter(x, y)
Out[39]:
No description has been provided for this image

PGFPlots gives you the option of picking a color for each scatter point. You can provide a third vector with the desired color values. The following code returns a Scatter plot where points with smaller z-values are blue. Points redden as the z-values increase.

In [40]:
z = 3x
Plots.Scatter(x, y, z)
Out[40]:
No description has been provided for this image

To add a colorbar, you can set the colorbar argument to true.

In [41]:
p = Plots.Scatter(x, y, z)
a = Axis(p, colorbar=true)
Out[41]:
No description has been provided for this image
In [42]:
print(tikzCode(a))
\begin{axis}[
  colorbar = {true}
]

\addplot+[
  scatter,
  scatter src = explicit,
  only marks = {true}
] coordinates {
  (1, 2) [3]
  (2, 4) [6]
  (3, 6) [9]
  (4, 8) [12]
  (5, 10) [15]
  (6, 12) [18]
  (7, 14) [21]
  (8, 16) [24]
  (9, 18) [27]
  (10, 20) [30]
};

\end{axis}

If you want non-numeric data to determine the coloration and marking of each scatter point, you must provide the scatterClasses argument and describe what each symbol means. This is the same string that would be passed into the tex file if you were writing it yourself. The following code colors points by their class ("a", "b", or "c").

In [43]:
z = ["a", "a", "a", "b", "b", "b", "b", "c", "c", "c"]
sc = "a={mark=square,blue}, b={mark=triangle,red}, c={mark=o,black}"
Plots.Scatter(x, y, z, scatterClasses=sc)
Out[43]:
No description has been provided for this image

You can add a legend using the legendentry keyword.

In [44]:
Plots.Scatter(x, y, z, scatterClasses=sc, legendentry=["A", "B", "C"])
Out[44]:
No description has been provided for this image

You can customize the legend using optionsto the Axis (since the legend style is a property of the Axis).

In [45]:
Axis(Plots.Scatter(x, y, z, scatterClasses=sc, legendentry=["A", "B", "C"]), style="legend columns = -1", legendPos="north west")
Out[45]:
No description has been provided for this image

Histograms¶

It is very easy to make histograms. It is just another type under the Plots module. You should be able to use autocompletion in your editor (e.g., IJulia) to see what Plots are supported.

In [46]:
d = randn(100)
a = Axis(Plots.Histogram(d, bins=10), ymin=0)
Out[46]:
No description has been provided for this image
In [47]:
print(tikzCode(a))
\begin{axis}[
  ymin = {0}
]

\addplot+[
  mark = none,
  fill=blue!10,
  hist = {density = {false}, cumulative = {false}, bins = {10}}
] table[
  row sep=\\,
  y index = 0
] { data \\
  -0.3759422970202321 \\ 
  1.418008304088542 \\ 
  -0.8469708281756384 \\ 
  -0.10449218604636919 \\ 
  0.7022345904153531 \\ 
  1.7110678188844222 \\ 
  2.1932490517941234 \\ 
  -0.1109625986726227 \\ 
  -1.190011521587443 \\ 
  0.6279091041281318 \\ 
  -2.120148790088747 \\ 
  0.2389548866297351 \\ 
  -2.670121861506243 \\ 
  -0.0645876270182514 \\ 
  -0.25520643028807233 \\ 
  0.3432227279891867 \\ 
  0.1927637601304434 \\ 
  1.0058614013159084 \\ 
  1.3034514614881438 \\ 
  0.29058821604099366 \\ 
  0.9268656570976852 \\ 
  -0.14798300983803905 \\ 
  -0.3079964890213105 \\ 
  -1.686250908782522 \\ 
  -0.014294715514785781 \\ 
  -1.7483654827294255 \\ 
  -1.0934709920649563 \\ 
  1.7376876731458128 \\ 
  0.9633386748243379 \\ 
  0.49045584258111774 \\ 
  -0.11346472289014338 \\ 
  0.5648658258209476 \\ 
  2.31127721367617 \\ 
  -0.4138003569668445 \\ 
  -0.6530363754485827 \\ 
  -0.3089724558821561 \\ 
  0.6860411705038941 \\ 
  -0.23703171353669777 \\ 
  0.4116268051344005 \\ 
  0.5809436812638662 \\ 
  -0.6400165976521003 \\ 
  1.1700056267042436 \\ 
  0.13852676820937598 \\ 
  0.6732554807927587 \\ 
  -0.7004267139023518 \\ 
  0.6055986170640195 \\ 
  0.5222913134223302 \\ 
  0.35035302769154725 \\ 
  0.33628303368920187 \\ 
  0.7656780028132334 \\ 
  0.6338248489475086 \\ 
  -0.5854369809506224 \\ 
  0.16410923652307347 \\ 
  -2.0981189052554514 \\ 
  -0.2504873061541892 \\ 
  -2.6242991432540914 \\ 
  0.16560298489706968 \\ 
  0.724614484909731 \\ 
  0.2809526533787639 \\ 
  0.8961448463466408 \\ 
  -0.44301601248782346 \\ 
  1.8112189629022108 \\ 
  0.21870559825977606 \\ 
  -1.0804423916258983 \\ 
  0.37902626039381826 \\ 
  -0.28598086411249823 \\ 
  -1.3873788996569327 \\ 
  -0.5801889528903655 \\ 
  -0.09184145050018341 \\ 
  -0.8840673103715921 \\ 
  0.04058043527139215 \\ 
  -0.07511810041957773 \\ 
  -0.7060280063729266 \\ 
  -2.0716323721002703 \\ 
  -0.2922003519262951 \\ 
  -1.1958297102195246 \\ 
  -1.4813385621313127 \\ 
  -0.48528362839649464 \\ 
  -1.8296859779941221 \\ 
  0.8348768662563161 \\ 
  0.6753234754263164 \\ 
  0.3571606534148708 \\ 
  -0.19289094051118819 \\ 
  -0.26955352558046186 \\ 
  -1.1169172332838055 \\ 
  -1.3263885048038995 \\ 
  -0.5913771679474423 \\ 
  0.2280515310703074 \\ 
  1.6924040454896017 \\ 
  1.6368681368904285 \\ 
  -0.5170483797115745 \\ 
  0.8969462106907216 \\ 
  0.3264541700400602 \\ 
  -0.5093095606768557 \\ 
  -0.5180139593461457 \\ 
  0.47556960165505063 \\ 
  1.6011108518341612 \\ 
  0.8141873207145738 \\ 
  0.1884943201898108 \\ 
  -1.3914730201040888 \\ 
};

\end{axis}

You can even create a cumulative distribution function from the data.

In [48]:
Axis(Plots.Histogram(d, bins=20, cumulative=true, density=true), ymin=0)
Out[48]:
No description has been provided for this image

As with the other plots, you can control the style. The documentation on tikz and pgfplots can give you more information about what styles are supported.

In [49]:
Axis(Plots.Histogram(d, bins=10, style="red, fill=red!10"), ymin=0, ylabel="Counts")
Out[49]:
No description has been provided for this image

Sometimes you do not want to store your raw dataset in a Tikz file, especially when the dataset is large. The discretization option lets you specify what discretization algorithm to use.

In [50]:
Axis(Plots.Histogram(d, discretization=:auto), ymin=0)
Out[50]:
No description has been provided for this image

Several discretization algorithms are provided by Discretizers.jl.

In [51]:
using Random
discretizations = 
           [:default, # use PGFPlots for small data sizes and :auto for large
            :pgfplots, # use the PGFPlots histogram function (uses nbins, which defaults to 10)
            :specified, # use Discretizers.jl but with the specified number of bins (which defaults to 10)
            :auto, # max between :fd and :sturges. Good all-round performance
            :fd, # Freedman Diaconis Estimator, robust
            :sturges, # R's default method, only good for near-Gaussian data
            :sqrt, # used by Excel and others for its simplicity and speed
            :doane, # improves Sturges’ for non-normal datasets.
            :scott, # less robust estimator that that takes into account data variability and data size.
            ]

Random.seed!(0)
data = [randn(500).*1.8 .+ -5;
        randn(2000).*0.8 .+ -4;
        randn(500).*0.3 .+ -1;
        randn(1000).*0.8 .+ 2;
        randn(500).*1.5 .+ 4;
       ]
data = filter!(x->-15.0 <= x <= 15.0, data)

g = GroupPlot(3, 3, groupStyle = "horizontal sep = 1.75cm, vertical sep = 1.5cm")
for discretization in discretizations
    push!(g, Axis(Plots.Histogram(data, discretization=discretization), ymin=0, title=string(discretization)))
end
g
Out[51]:
No description has been provided for this image

Bar Charts¶

Bar charts differ from histograms in that they represent values assigned to distinct items. A BarChart has keys and values.

In [52]:
p = Plots.BarChart(["a", "b"], [1,2])
Out[52]:
No description has been provided for this image
In [53]:
print(tikzCode(p))
\begin{axis}[
  ybar = 0pt,
  bar width = 18pt,
  xtick = data,
  symbolic x coords = {a, b},
  ymin = {0}
]

\addplot+ coordinates {
  (a, 1)
  (b, 2)
};

\end{axis}

If only values are passed in, the keys will be set to the first $n$ integers.

In [54]:
Plots.BarChart([3,4,5,2,10])
Out[54]:
No description has been provided for this image

Vectors of AbstractStrings will be counted and the strings used as keys.

In [55]:
Plots.BarChart(["cat", "dog", "cat", "cat", "dog", "mouse"])
Out[55]:
No description has been provided for this image
In [56]:
Plots.BarChart([L"x", L"x^2", L"x^2", L"sin(x)", "hello world"])
Out[56]:
No description has been provided for this image
In [57]:
Axis(Plots.BarChart(["potayto", "potahto", "tomayto", "tomahto"], [1,2,3,4], style="cyan"),
     xlabel="vegetables", ylabel="counts", style="bar width=25pt")
Out[57]:
No description has been provided for this image

Error bars on the value can be added using the errorBars keyword.

In [58]:
Plots.BarChart(["a", "b", "c"], [2, 3, 5], errorBars=ErrorBars(y=[0.5, 0.7, 1.5]))
Out[58]:
No description has been provided for this image

Images¶

Image plots create a PNG bitmap and can be used to visualize functions. The second and third arguments below are tuples specifying the x and y ranges.

In [59]:
f = (x,y)->x*exp(-x^2-y^2)
p = Plots.Image(f, (-2,2), (-2,2))
Out[59]:
No description has been provided for this image
In [60]:
print(tikzCode(p))
\begin{axis}[
  enlargelimits = false,
  axis on top,
  colormap={wb}{gray(0cm)=(0); gray(1cm)=(1)},
  colorbar
]

\addplot[
  point meta min = -0.42870694108441587,
  point meta max = 0.42870694108441587
] graphics[
  xmin = -2,
  xmax = 2,
  ymin = -2,
  ymax = 2
] {tmp_10000000000001.png};

\end{axis}

You can set the zmin and zmax. By default, it uses the minimum and maximum values of the data.

In [61]:
Plots.Image(f, (-2,2), (-2,2), zmin=-1, zmax=1)
Out[61]:
No description has been provided for this image

You can invert the Gray colormap.

In [62]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.GrayMap(invert = true))
Out[62]:
No description has been provided for this image

You can turn off the colorbar.

In [63]:
Plots.Image(f, (-2,2), (-2,2), colorbar = false)
Out[63]:
No description has been provided for this image

You can change the colormap.

In [64]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.Distinguishable(3))
Out[64]:
No description has been provided for this image
In [65]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.Distinguishable(4))
Out[65]:
No description has been provided for this image
In [66]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.Distinguishable(4, invert=true))
Out[66]:
No description has been provided for this image

You can use colormap names from the Color.jl package.

In [67]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.Named("Blues"))
Out[67]:
No description has been provided for this image

You can make a colormap out of any RGB array, such as those created from the Color.jl package.

In [68]:
using Colors
cm = colormap("RdBu")
Out[68]:
No description has been provided for this image
In [69]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.RGBArrayMap(cm))
Out[69]:
No description has been provided for this image

You can also choose the Jet colormap (not currently part of Colors.jl).

In [70]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.Named("Jet"))
Out[70]:
No description has been provided for this image

You can also use colors from ColorBrewer.jl.

In [71]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.Brew("Set1", 3))
Out[71]:
No description has been provided for this image

And you can invert them.

In [72]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.Brew("Set1", 3, invert=true))
Out[72]:
No description has been provided for this image

You can specify colors manually.

In [73]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.RGBArrayMap([RGB(1.,0.,0.),RGB(0.,1.,0.), RGB(0.,0.,1.)]))
Out[73]:
No description has been provided for this image

You can specify the number of interpolation levels. Here, we specify 500.

In [74]:
Plots.Image(f, (-2,2), (-2,2), colormap = ColorMaps.RGBArrayMap([RGB(1.,0.,0.),RGB(0.,1.,0.), RGB(0.,0.,1.)], interpolation_levels=500))
Out[74]:
No description has been provided for this image

Instead of a function, you can pass in a matrix.

In [75]:
A = [1 3; 2 10]
Plots.Image(A, (-2,2), (-2,2))
Out[75]:
No description has been provided for this image

Patch2D¶

The Patch2D type produces patch plots consisting of colored triangles or rectangles.

Here we see three triangles, each defined by three (x,y) coordinates.

In [76]:
p = Plots.Patch2D([0 1 2     1 2 3     2 3 4;  # x
                   0 1 0     1 0 1     0 1 0]) # y
Out[76]:
No description has been provided for this image

Color can also be added as a third row.

In [77]:
p = Plots.Patch2D([0   1 2     1 2 3     2 3 4;    # x
                   0   1 0     1 0 1     0 1 0;    # y
                   0.2 0 1     0 1 0     1 0 0.5]) # color
Out[77]:
No description has been provided for this image
In [78]:
p = Plots.Patch2D([0   1 2     1 2 3     2 3 4;    # x
                   0   1 0     1 0 1     0 1 0;    # y
                   0.2 0 1     0 1 0     1 0 0.5], # color
                  shader = "interp")
Out[78]:
No description has been provided for this image
In [79]:
p = Plots.Patch2D([0   1 2     1  2 3     2   3 4;    # x
                   0   1 0     1  0 1     0   1 0;    # y
                   0.2 0 1     0 -1 0     0.5 1 0.5], # color
                  shader = "interp")
Out[79]:
No description has been provided for this image

Rectangular patches can be used as well:

In [80]:
p = Plots.Patch2D([0   1 1 0     1  2 2 1    1   2 2   1;  # x
                   0   0 1 1     0  0 1 1    1   1 2   2;  # y
                   0.2 0 1 1     0 -1 0 1    0.5 1 0.5 0], # color
                  shader = "interp", patch_type="rectangle")
Out[80]:
No description has been provided for this image
In [81]:
print(tikzCode(p))
\begin{axis}

\addplot[
  patch type = {rectangle},
  shader = {interp},
  patch
] table[
  point meta = \thisrow{c}
] {
  x y c
  0 0 0.2
  1 0 0
  1 1 1
  0 1 1

  1 0 0
  2 0 -1
  2 1 0
  1 1 1

  1 1 0.5
  2 1 1
  2 2 0.5
  1 2 0

};

\end{axis}

Colormaps can be added by the axis.

Histogram2¶

You may produce 2-dimensional histograms from a set of (x,y) datapoints. Uniform spacing will be assumed if bin edges are not provided. In this case an Image will be returned.

In [82]:
x = randn(10000)*2 .+ 1
y = randn(10000) .- 2
Plots.Histogram2(x, y)
Out[82]:
No description has been provided for this image

You can customize the limits and the colormap.

In [83]:
Plots.Histogram2(x, y, xmin=-3, xmax=3, ymin=-3, ymax=3, zmin=-1, colormap=ColorMaps.Named("Jet"))
Out[83]:
No description has been provided for this image

You can also customize the bounds of the colormap.

In [84]:
Plots.Histogram2(x, y, xmin=-3, xmax=3, ymin=-3, ymax=3, zmin=5, zmax=15, colormap=ColorMaps.Named("Jet"))
Out[84]:
No description has been provided for this image

The axis image can be made equal.

In [85]:
Axis(Plots.Histogram2(x, y, density=true, xmin=-3, xmax=3, ymin=-3, ymax=3), axisEqualImage=true)
Out[85]:
No description has been provided for this image

Instead of counts, you can transform the scale to reflect a probability density.

In [86]:
Plots.Histogram2(x, y, density=true)
Out[86]:
No description has been provided for this image

Instead of counts, you can transform the scale to reflect the log of the counts. Counts are often 0 and log(0) = -Inf, so by default, the minimum is set to half of the minimum count value greater than 0.

In [87]:
Plots.Histogram2(x, y, zmode="log")
Out[87]:
No description has been provided for this image

The minimum can also be input.

In [88]:
p = Plots.Histogram2(x, y, zmode="log", zmin=1.)
Out[88]:
No description has been provided for this image
In [89]:
print(tikzCode(p))
\begin{axis}[
  enlargelimits = false,
  axis on top,
  colormap={wb}{gray(0cm)=(0); gray(1cm)=(1)},
  colorbar,
  colorbar style = {ymode = log, scaled ticks = false}
]

\addplot[
  point meta min = 1.0,
  point meta max = 44.0
] graphics[
  xmin = -6.564662688561218,
  xmax = 8.269642637488749,
  ymin = -5.816835592811515,
  ymax = 1.7421055258131708
] {tmp_10000000000022.png};

\end{axis}

Uneven Bins¶

Bin edges can be provided, in which case a Patch2D is created.

In [90]:
x = randn(10000).+1.0
y = randn(10000)
edges_x = [-3.0,-1.0,0.0,0.5,0.75,1.0,1.25,1.5,2.0,3.0]
edges_y = range(-3.0,stop=3.0,length=11)
p = Plots.Histogram2(x, y, edges_x, edges_y, density=true, style="colormap/blackwhite")
Axis(p, enlargelimits=0)
Out[90]:
No description has been provided for this image

Contour¶

The syntax for contours is similar to that of image.

In [91]:
Plots.Contour(f, (-2,2), (-2,2))
Out[91]:
No description has been provided for this image

You can specify the levels explicitly.

In [92]:
Plots.Contour(f, (-2,2), (-2,2), levels=-0.4:0.1:4)
Out[92]:
No description has been provided for this image

You can also just specify the number of contours you want.

In [93]:
Plots.Contour(f, (-2,2), (-2,2), number=20)
Out[93]:
No description has been provided for this image

You can specify styles.

In [94]:
Plots.Contour(f, (-2,2), (-2,2), style="very thick")
Out[94]:
No description has been provided for this image

You can pass in a matrix instead of a function.

In [95]:
x = range(-2,stop=2)
y = range(-2,stop=2)
A = Float64[f(xi, yi) for xi in x, yi in y]
Plots.Contour(A, x, y)
Out[95]:
No description has been provided for this image

Here is another example.

In [96]:
Plots.Contour(randn(11,11), 0:10, 0:10)
Out[96]:
No description has been provided for this image

In LaTeX, a Contour plot has two style fields - one for the plot3 and one for the contour itself.

\addplot3[contour prepared={...}, ...] table {...};

To set properties of the contour lines one needs to insert them inside the countour prepared={}. These styles are set in contour_style. Remaining properties can still be set in style.

In [97]:
Plots.Contour(f, (-2,2), (-2,2), contour_style="draw color=cyan", style="dashed")
Out[97]:
No description has been provided for this image

Surface¶

The syntax for surfaces is similar to that of contour.

In [98]:
Plots.Surface(f, (-2,2), (-2,2))
Out[98]:
No description has been provided for this image

You can pass in a matrix instead of a function.

In [99]:
x = range(-2,stop=2)
y = range(-2,stop=2)
A = Float64[f(xi, yi) for xi in x, yi in y]
Plots.Surface(A, x, y)
Out[99]:
No description has been provided for this image

You can use the colorbar field to show a colorbar which indicates the value associated with different colors on the surface.

In [100]:
s = Plots.Surface(f, (-2,2), (-2,2))
PGFPlots.Axis(s, colorbar=true)
Out[100]:
No description has been provided for this image

Here is another example.

In [101]:
Plots.Surface(randn(11,11), 0:10, 0:10)
Out[101]:
No description has been provided for this image

Quiver¶

In [102]:
h(x,y) = [exp(-x^2-y^2)*(1-2*x^2), exp(-x^2-y^2)*(-2*x*y)]
Plots.Quiver(h,(-2,2),(-2,2))
Out[102]:
No description has been provided for this image
In [103]:
h2(x,y) = [exp(-x^2-y^2)*(1-2*x^2), exp(-x^2-y^2)*(-2*x*y)]
Plots.Quiver(h2,(-2,2),(-2,2), style="-stealth'")
Out[103]:
No description has been provided for this image

By default, the length of the arrows are normalized so that they do not overlap each other. This can be turned off.

In [104]:
Plots.Quiver(h,(-2,2),(-2,2), normalize=false)
Out[104]:
No description has been provided for this image

MatrixPlot¶

Similar to Image, MatrixPlot is a new function in PGFPlots specifically for plotting matrices as arrays of colors. This can be used to quickly make heatmaps as well.

In [105]:
A = [1 3; 2 10]
p = Plots.MatrixPlot(A)
Out[105]:
No description has been provided for this image
In [106]:
print(tikzCode(p))
\begin{axis}[
  enlargelimits = false,
  axis on top,
  colormap={wb}{gray(0cm)=(0); gray(1cm)=(1)},
  colorbar,
  xmin = 0.5,
  xmax = 2.5,
  ymin = 0.5,
  ymax = 2.5
]

\addplot[
  point meta min = 1,
  point meta max = 10,
  point meta = explicit,
  matrix plot*,
  mesh/cols = 2,
  mesh/rows = 2
] table[
  meta = data
] {tmp_10000000000023.dat};

\end{axis}

Here is a larger matrix.

In [107]:
A = rand(50,50)
Plots.MatrixPlot(A)
Out[107]:
No description has been provided for this image

As with Image you can specify axis limits as tuples, but this is not required in the case of matrices.

In [108]:
Plots.MatrixPlot(A,(-2,2),(-2,2))
Out[108]:
No description has been provided for this image

All the same colorbar arguements as Image still apply, including loading other colormaps.

In [109]:
Plots.MatrixPlot(A,(-2,2),(-2,2),colormap = ColorMaps.Named("Jet"))
Out[109]:
No description has been provided for this image

Similarly you can specify your own colors to make custom colormaps.

In [110]:
cm = ColorMaps.RGBArrayMap([RGB(1.,0.,0.),RGB(1.,1.,1.), RGB(0.,0.,1.)], interpolation_levels=500)
Plots.MatrixPlot(A,(-2,2),(-2,2),colormap = cm)
Out[110]:
No description has been provided for this image

However one advantage of using MatrixPlot is the abilty to handle NaN values, resulting in blank spots.

In [111]:
A[20:30,20:30] .= NaN
Plots.MatrixPlot(A,(-2,2),(-2,2),colormap = cm)
Out[111]:
No description has been provided for this image

This comes with an unfortunate tradeoff, since the plotting time purely through PGFPlots for large arrays is untenable to regular use. When an input matrix has a total length greater than 10000, PGFPlots.jl will fallback to rendering a PNG bitmap instead.

In [112]:
A = rand(120,120)
Plots.MatrixPlot(A,(-2,2),(-2,2),colormap = cm)
┌ Warning: Matrix is too large for vector plotting, consider switching to raster mode.
└ @ PGFPlots.Plots ~/Downloads/PGFPlots.jl-1/src/plots.jl:554
Out[112]:
No description has been provided for this image

This fallback can be disabled by setting the key raster=false, forcing PGFPlots to render the matrix.

Group plots¶

A GroupPlot is just a container for plots. You can specify the number or columns and rows to use.

In [113]:
# generate 1000 samples
d = randn(1000)
# try out histograms with a variety of different number of bins
bins = [3 10 50 1000]
g = GroupPlot(2,2) # create a 2 x 2 group plot
for i = 1:length(bins)
    push!(g, Axis(Plots.Histogram(d, bins=bins[i]), ymin=0))
end
g
Out[113]:
No description has been provided for this image

You can set the group style.

In [114]:
g = GroupPlot(2, 2, groupStyle = "horizontal sep = 3cm") # create a 2 x 2 group plot
for i = 1:length(bins)
    push!(g, Axis(Plots.Histogram(d, bins=bins[i]), ymin=0))
end
g
Out[114]:
No description has been provided for this image

Multiple Axes¶

An alternative to group plots is to use multiple axes. This is not as user friendly as group plots, but it allows for more flexibility. For example, it is possible to embed one axis inside another to create insets as follows:

In [115]:
#Create the first axis and add to it two lines
a1 = PGFPlots.Axis(style="width=10cm, height=10cm, grid=both");
push!(a1, PGFPlots.Linear([1,2],[10, 10], style="blue"))
push!(a1, PGFPlots.Linear([1,2],[10, 3],  style="red"))

#Create another axis with smaller width.
#xshift and yshift are used to position the axis.
a2 = PGFPlots.Axis(style="width=4cm, xshift=1cm, yshift=1cm", title="xy reflection");
push!(a2, PGFPlots.Linear([10, 10], [1,2], style="no marks, blue, thick"))
push!(a2, PGFPlots.Linear([10, 3] , [1,2], style="no marks, red, thick"));

#Group the two axes together as a list
[a1, a2]
Out[115]:
No description has been provided for this image

Text Nodes¶

In [116]:
Axis([
    Plots.Image(f, (-2,2), (-2,2)),
    Plots.Node(L"\sqrt{2}",1,0)        
])
Out[116]:
No description has been provided for this image
In [117]:
Axis([
    Plots.Image(f, (-2,2), (-2,2)),
    Plots.Node(L"\sqrt{2}",-1,0,style="yellow"),        
    Plots.Node("Hi there!",1,0,style="right")        
])
Out[117]:
No description has been provided for this image

The coordinate system defaults to the axis coordinate system, axis cs. You can specify other coordinate systems as well.

In [118]:
Axis([
    Plots.Image(f, (-2,2), (-2,2)),
    Plots.Node(L"\sqrt{2}",0.9,0.9,axis="axis description cs")
])
Out[118]:
No description has been provided for this image

Circles and Ellipses¶

You can add circles and ellipses to your plots. To add a circle, you must specify the center x-coordinate, the center y-coordinate, and the radius, in that order. To add an ellipse, you must specify the center x-coordinate, the center y-coordinate, the x-radius, and the y-radius.

In [119]:
p1 = Plots.Circle(5,5,5)
p2 = Plots.Ellipse(5,5,3,5)
Axis([p1,p2], xmin=0,ymin=0,xmax=10,ymax=10)
Out[119]:
No description has been provided for this image

You can remove axes if you want to. Remove the axes (hide the axes) by setting hideAxis to true for the axis.

In [120]:
a = Axis([p1,p2], xmin=0,ymin=0,xmax=10,ymax=10, hideAxis=true)
Out[120]:
No description has been provided for this image
In [121]:
print(tikzCode(a))
\begin{axis}[
  xmin = {0},
  xmax = {10},
  ymax = {10},
  hide axis = {true},
  ymin = {0}
]

\draw (axis cs:5, 5) circle[radius=5];

\draw (axis cs:5, 5) ellipse[x radius=3, y radius=5];

\end{axis}

3d Plots¶

You can add 3d plots. To make a 3d plot with a linear scale, use the Linear3 type (equivalent to \addplot3 in PGF).

In [122]:
t = rad2deg.(range(0,stop=5pi,length=60))
x = sind.(t)
y = cosd.(t)
z = 2t/(5pi)
p = Plots.Linear3(x, y, z, mark="none")
Axis(p, xlabel="x", ylabel="y", zlabel="z")
Out[122]:
No description has been provided for this image

You can change the view by specifying the view parameter of the Axis type. This is a string representing what you would feed to PGF. The first parameter is the rotation about the azimuth (z-axis). This rotation is applied first. The second argument is the elevation, or the angle rotated about the (rotated) x-axis.

In [123]:
Axis(p, view="{60}{30}", xlabel="x", ylabel="y", zlabel="z")
Out[123]:
No description has been provided for this image

Polar Axes¶

You can specify a polar axis. In this case, the "x" coordinate corresponds to the angle (in degrees), and the "y" coordinate corresponds to the radius.

In [124]:
angles = [0,90,180,270]
radii = ones(4)
p = Plots.Linear(angles, radii)
PolarAxis(p)
Out[124]:
No description has been provided for this image

Smith Charts¶

You can create Smith charts. These are often used in RF engineering. The SmithAxis type produces the axis, whereas the SmithCircle type is a convenient way to render circles.

In [125]:
SmithAxis([
    PGFPlots.SmithCircle(1.0, 1.0, 2.0, style="blue"),
    PGFPlots.SmithCircle(0.5, -1.0, 1.0, style="red"),
])
Out[125]:
No description has been provided for this image

The SmithData type allows for more complicated plots. Support is provided for several types of arrays, including complex numbers and 2d arrays.

In [126]:
SmithAxis(PGFPlots.SmithData([0+0im, 0.5+0.5im, 1.0+0.5im, 1.0+1.0im], 
          style="thick, blue"))
Out[126]:
No description has been provided for this image

Ternary Axis¶

You can specify a ternary axis. These are special three-dimensional plots often used to show the space of 3D categorical distributions. One thus commonly uses 3D plots such as Linear3 within a ternary axis.

In [127]:
TernaryAxis(
    Plots.Linear3([0.1,0.4],[0.3,0.2],[0.6,0.4],style="solid, blue, thick"),
    style="ternary limits relative=false",
    xlabel=L"b_1",
    ylabel=L"b_2",
    zlabel=L"b_3"
)
Out[127]:
No description has been provided for this image

Color¶

You can define your own custom named colors using a variety of methods. You can pass it an array of FloatingPoint values in the range $[0,1]$; it uses RGB if there are three values, and it uses CMYK if there are four values.

In [128]:
define_color("myrgbcolor1", [1,0.2,0.3])
Plots.Linear(x, y, style="myrgbcolor1")
Out[128]:
No description has been provided for this image
In [129]:
define_color("mycmykcolor1", [1,0.2,0.3,0])
Plots.Linear(x, y, style="mycmykcolor1")
Out[129]:
No description has been provided for this image

If you pass in an array of integers (between 0 and 255), then it will use the integer-based RGB color space.

In [130]:
define_color("myRGBcolor", [82,227,246])
Plots.Linear(x, y, style="myRGBcolor")
Out[130]:
No description has been provided for this image

If you pass in a single scalar value between 0 and 1, it will interpret as a shade of gray. In this scale, 0 is black and 1 is white.

In [131]:
define_color("mylightgray", 0.9)
Plots.Linear(x, y, style="mylightgray")
Out[131]:
No description has been provided for this image

If you pass in a UInt32, you will get an HTML color.

In [132]:
define_color("myhtmlcolor", 0xff7f00)
Plots.Linear(x, y, style="myhtmlcolor")
Out[132]:
No description has been provided for this image

You can also pass in any color type from the Colors.jl and ColorTypes.jl packages.

In [133]:
define_color("mycolor", HSV(300, 0.2, 0.9))
Plots.Linear(x, y, style="mycolor, very thick")
Out[133]:
No description has been provided for this image

DataFrames¶

PGFPlots provides support for plotting from DataFrames.

In [134]:
using DataFrames

df = DataFrame(x=[1,2,3], y=[2,4,1], z=[0.0,0.5,1.0])
df_big = DataFrame(x=randn(1000), y=randn(1000))
df_quiver = DataFrame(x=[0,0,1,1], y=[0,1,0,1], u=[0.25,0.25,-0.25,-0.25], v=[0.25,-0.25,0.25,-0.25])

g = GroupPlot(3, 3, groupStyle = "horizontal sep = 1.75cm, vertical sep = 1.5cm")
push!(g, Axis(Plots.Linear(df), title="Linear"))
push!(g, Axis(Plots.Linear(df, x=:y, y=:z, style="red", mark="none"), title="Linear with Options"))
push!(g, Axis(Plots.Linear3(df), title="Linear3"))
push!(g, Axis(Plots.Scatter(df), title="Scatter"))
push!(g, Axis(Plots.Histogram(df_big), title="Histogram"))
push!(g, Axis(Plots.Quiver(df_quiver), title="Quiver"))
push!(g, Axis(Plots.Histogram2(df_big), title="Histogram2 - Image"))
push!(g, Axis(Plots.Histogram2(df_big, Float64[-3,-1,1,3], Float64[-3,-2,-1,0,1,2,3], style="colormap/blackwhite"), enlargelimits=0, title="Histogram2 = Patch2D"))
g
Out[134]:
No description has been provided for this image

The constructors default to symbol names such as x, y, z, and u and v for quiver plots. These can be assigned as normal.

In [135]:
df = DataFrame(position=[0.0,0.5,1.5,4.0], time=[0.0,1.0,2.0,3.0])
Axis(Plots.Linear(df, x=:time, y=:position), xlabel="time [s]", ylabel="position [m]")
Out[135]:
No description has been provided for this image

Commands¶

You can inject arbitrary latex commands within an axis using Plots.Command. Below is an example. Of course, in this particular example, it is easier to use the legendentry keyword.

In [136]:
Axis([
    Plots.Linear(x, y, style="mycolor, very thick"),
    Plots.Command("\\legend{Test}")
])
Out[136]:
No description has been provided for this image

Customizing Preamble¶

In order to customize the $\LaTeX$ preamble in the current context, you can call pushPGFPlotsPreamble. For example, suppose you want to use the "xfrac" package:

In [137]:
pushPGFPlotsPreamble("\\usepackage{xfrac}")
Plots.Linear(x, y, legendentry = L"\sfrac{1}{x}")
Out[137]:
No description has been provided for this image

To remove the latest option, just call popPGFPlotsPreamble(). All options can be reset with resetPGFPlotsPreamble()

In [138]:
popPGFPlotsPreamble()
Plots.Linear(x, y, legendentry = "Test")
Out[138]:
No description has been provided for this image

Another common application is to obtain the \text macro from the amsmath package:

In [139]:
pushPGFPlotsPreamble("\\usepackage{amsmath}")
Axis(Plots.Linear([1,2], [1,2]), xlabel=L"x_\text{awesome}", ylabel="\$\\text{mathOperation}(x)\$")
Out[139]:
No description has been provided for this image

Saving¶

All of the images above can be saved in tex, pdf, or svg format.

In [140]:
p = Plots.Histogram(rand(10))
save("myfile.tex", p)
save("myfile.pdf", p)
save("myfile.svg", p)
┌ Warning: myfile.pdf already exists, overwriting!
└ @ TikzPictures ~/.julia/packages/TikzPictures/9WzZq/src/TikzPictures.jl:347
┌ Warning: myfile.svg already exists, overwriting!
└ @ TikzPictures ~/.julia/packages/TikzPictures/9WzZq/src/TikzPictures.jl:432

The preamble around tikzpicture can be ignored. This is useful if the plot will be \input{} in another document.

In [141]:
p = Plots.Histogram(rand(10))
save("myfile.tex", p, include_preamble=false)

Reel¶

PGFPlots.jl provides a image/svg+xml MIME for Reel. This allows one to create movies and GIFs. Here is an example:

using Reel
Reel.extension(m::MIME"image/svg+xml") = "svg"
Reel.set_output_type("gif") # may be necessary for use in IJulia

frames = Frames(MIME("image/svg+xml"), fps=10)
for frame in 1:10
    t = frame/5
    ax = Axis(Plots.Linear(x -> sin(x+t*π), (0,6)), xlabel="x", ylabel="y")
    push!(frames, ax)
end 
frames;

No description has been provided for this image

Future Plans¶

Gradually, more and more functionality from pgfplots will be migrated into this package.